<template>
  <div class="user-management">

    <el-card class="user-management-container">
      <!-- 查询表单 -->
      <el-form :model="searchForm" ref="searchFormRef" :inline="true">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="searchForm.username" placeholder="请输入用户名" clearable style="width: 150px;" />
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="searchForm.realName" placeholder="请输入真实姓名" clearable style="width: 150px;" />
        </el-form-item>
        <el-form-item label="部门" prop="deptId">
          <el-select v-model="searchForm.deptId" placeholder="请选择部门" clearable style="min-width: 120px;">
            <el-option v-for="dept in departmentOptions" :key="dept.id" :label="dept.name" :value="dept.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="角色" prop="roleId">
          <el-select v-model="searchForm.roleId" placeholder="请选择角色" clearable style="min-width: 120px;">
            <el-option v-for="role in roleOptions" :key="role.id" :label="role.name" :value="role.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="min-width: 120px;">
            <el-option label="启用" value=1 />
            <el-option label="禁用" value=0 />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 操作按钮 -->
      <div class="operation-buttons">
        <el-button type="primary" @click="showAddDialog">新增用户</el-button>
      </div>

      <!-- 用户表格 -->
      <el-table :data="userList" border style="width: 100%">
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="realName" label="真实姓名" width="120" />
        <el-table-column prop="deptName" label="部门" width="150" />
        <el-table-column prop="roleNames" label="角色" width="180">
          <template #default="{ row }">
            <el-tag v-for="role in row.roleNames" :key="role" size="small" style="margin-right: 5px">
              {{ role }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="120">
          <template #default="{ row }">
            <el-button size="small" :type="row.status === 1 ? 'success' : 'danger'" @click="toggleUserStatus(row)">
              {{ row.status === 1 ? '启用中' : '已禁用' }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="showDetailDialog(row.userId)">查看</el-button>
            <el-button size="small" type="primary" @click="showDetailDialog(row.userId, true)">编辑</el-button>
            <el-button size="small" @click="showResetPasswordDialog(row.userId)">重置密码</el-button>
            <el-popconfirm title="确认删除该用户吗？" @confirm="handleDelete(row.userId)">
              <template #reference>
                <el-button size="small" type="danger">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
          :total="pagination.total" :page-sizes="[2, 5, 10, 20]" layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑用户' : '新增用户'" width="50%">
      <el-form :model="userForm" ref="userFormRef" label-width="100px" :rules="userFormRules">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!isEdit">
          <el-input v-model="userForm.password" type="password" show-password />
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="userForm.realName" />
        </el-form-item>
        <el-form-item label="部门" prop="deptId">
          <el-select v-model="userForm.deptId" placeholder="请选择部门" clearable >

            <el-option v-for="dept in departmentOptions" :key="dept.id" :label="dept.name" :value="dept.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" />
        </el-form-item>
        <el-form-item label="电话号码" prop="phone">
          <el-input v-model="userForm.phone" />
        </el-form-item>
        <el-form-item label="角色" prop="roleIds">
          <el-select v-model="userForm.roleIds" multiple placeholder="请选择角色">
            <el-option v-for="role in roleOptions" :key="role.id" :label="role.name" :value="role.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="身份证号" prop="idCard">
          <el-input v-model="userForm.idCard" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 用户详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="用户详情" width="50%">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="用户ID">{{ userDetail.userId }}</el-descriptions-item>
        <el-descriptions-item label="用户名">{{ userDetail.username }}</el-descriptions-item>
        <el-descriptions-item label="真实姓名">{{ userDetail.realName }}</el-descriptions-item>
        <el-descriptions-item label="部门">{{ userDetail.deptName }}</el-descriptions-item>
        <el-descriptions-item label="角色">
          <el-tag v-for="role in userDetail.roleNames" :key="role" size="small" style="margin-right: 5px">
            {{ role }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="邮箱">{{ userDetail.email }}</el-descriptions-item>
        <el-descriptions-item label="电话号码">{{ userDetail.phone }}</el-descriptions-item>
        <el-descriptions-item label="身份证号">{{ userDetail.idCard }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          {{ userDetail.status === 1 ? '启用' : '禁用' }}
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ userDetail.createdTime }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ userDetail.updatedTime }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="editCurrentUser(userDetail.userId)">编辑</el-button>

        </span>
      </template>
    </el-dialog>

    <!-- 重置密码对话框 -->
    <el-dialog v-model="resetPasswordDialogVisible" title="重置密码" width="30%">
      <el-form :model="resetPasswordForm" ref="resetPasswordFormRef" label-width="100px" :rules="resetPasswordRules">
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="resetPasswordForm.newPassword" type="password" show-password />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="resetPasswordForm.confirmPassword" type="password" show-password />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="resetPasswordDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmResetPassword">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { UserApi } from '@/api/user.js'
import { DepartmentApi } from '@/api/department.js'

import { RoleApi } from '@/api/role.js'


// 查询表单
const searchForm = reactive({
  username: '',
  realName: '',
  deptId: '',
  roleId: '',
  status: ''

})

const searchFormRef = ref(null)

// 分页信息
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 用户列表
const userList = ref([])

// 部门选项
const departmentOptions = ref([])

// 角色选项
const roleOptions = ref([])

// 用户表单
const userForm = reactive({
  id: '',
  username: '',
  password: '',
  realName: '',
  deptId: '',
  email: '',
  phone: '',
  roleIds: [],
  idCard: '',
  status: ''
})

const userFormRef = ref(null)

// 表单验证规则
const userFormRules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' }
  ],
  deptId: [
    { required: false, message: '请选择部门', trigger: 'change' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  roleIds: [
    { required: true, message: '请至少选择一个角色', trigger: 'change' }
  ],
  idCard: [
    { pattern: /^\d{17}[\dXx]$/, message: '请输入正确的身份证号码', trigger: 'blur' }
  ]
})

// 对话框控制
const dialogVisible = ref(false)
const detailDialogVisible = ref(false)
const resetPasswordDialogVisible = ref(false)
const isEdit = ref(false)

// 当前操作用户
const currentUser = ref({})

// 重置密码表单
const resetPasswordForm = reactive({
  userId: '',
  newPassword: '',
  confirmPassword: ''
})

const resetPasswordFormRef = ref(null)

// 重置密码表单验证规则
const resetPasswordRules = reactive({
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    { validator: (rule, value, callback) => {
        if (value !== resetPasswordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'));
        } else {
          callback();
        }
      }, trigger: 'blur' }
  ]
});

const userDetail = ref({})

// 初始化数据
onMounted(async () => {
  const result1 = await DepartmentApi.getDepartmentList()
  const result2 = await RoleApi.getRoleList()
  const result3 = await UserApi.getUserListByPage()
  departmentOptions.value = result1.data.records
  roleOptions.value = result2.data
  userList.value = result3.data.records
})

// 查询
const handleSearch = async () => {
  // 构建查询参数
  const params = {
    pageNum: pagination.currentPage,
    pageSize: pagination.pageSize,
    username: searchForm.username,
    realName: searchForm.realName,
    deptId: searchForm.deptId,
    roleId: searchForm.roleId,
    status: searchForm.status
  }
  console.log(params)

  const result = await UserApi.getUserListByPage(params)
  userList.value = result.data.records
  pagination.total = result.data.totalRow

}

// 重置查询
const resetSearch = () => {
  searchFormRef.value.resetFields()
  handleSearch()
}

// 分页大小改变
const handleSizeChange = (val) => {
  pagination.pageSize = val
  handleSearch()
}

// 当前页改变
const handleCurrentChange = (val) => {
  pagination.currentPage = val
  handleSearch()
}

// 显示新增对话框
const showAddDialog = () => {
  isEdit.value = false
  resetForm()
  dialogVisible.value = true
}

// 显示详情对话框
const showDetailDialog = async (userId, edit = false) => {
  if (edit) {
    editCurrentUser(userId)
    return
  }
  const result = await UserApi.getUserDetail(userId)
  userDetail.value = result.data
  detailDialogVisible.value = true

}

// 编辑当前用户
const editCurrentUser = async (userId) => {

  detailDialogVisible.value = false
  resetForm()
  isEdit.value = true
  const result = await UserApi.getUserDetail(userId)
  // 填充表单
  Object.assign(userForm, {
    id: result.data.userId,
    username: result.data.username,
    password: result.data.password,
    realName: result.data.realName,
    deptId: result.data.deptId,
    email: result.data.email,
    phone: result.data.phone,
    roleIds: result.data.roleIds,
    idCard: result.data.idCard,
    status: result.data.status
  })

  dialogVisible.value = true
}

// 重置表单
const resetForm = () => {
  userFormRef.value?.resetFields()
  Object.assign(userForm, {
    id: '',
    username: '',
    password: '',
    realName: '',
    deptId: '',
    email: '',
    phone: '',
    roleIds: [],
    idCard: '',
    status: ''
  })
}

// 提交表单
const submitForm = () => {
  userFormRef.value.validate(valid => {
    if (valid) {
      if (isEdit.value) {
        UserApi.updateUser(userForm).then(() => {
          ElMessage.success('用户更新成功')
          handleSearch()
        })
      } else {
        UserApi.createUser(userForm).then(() => {
          ElMessage.success('用户添加成功')
          handleSearch()
        })
      }
      dialogVisible.value = false
    }
  })
}

// 切换用户状态
const toggleUserStatus = (user) => {
  const newStatus = user.status === 1 ? 0 : 1
  const action = newStatus === 1 ? '启用' : '禁用'

  ElMessageBox.confirm(`确认${action}用户 ${user.username} 吗？`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    UserApi.updateStatus({ id: user.userId, status: newStatus }).then(() => {
      ElMessage.success(`用户${action}成功`)
      handleSearch()
    })
  }).catch(() => {
    ElMessage.info('已取消操作')
  })
}

// 删除用户
const handleDelete = (userId) => {
  ElMessageBox.confirm('确认删除用户吗？', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    UserApi.deleteUser(userId).then(() => {
      ElMessage.success('用户删除成功')
      handleSearch()
    })
  }).catch(() => {
    ElMessage.info('已取消操作')
  })
}

// 显示重置密码对话框
const showResetPasswordDialog = (userId) => {
  resetPasswordFormRef.value?.resetFields()
  resetPasswordForm.userId = userId
  resetPasswordDialogVisible.value = true
}

// 确认重置密码
const confirmResetPassword = () => {
  resetPasswordFormRef.value.validate(valid => {
    if (valid) {
      UserApi.resetPassword({ userId: resetPasswordForm.userId, newPassword: resetPasswordForm.newPassword }).then(() => {
        ElMessage.success('密码重置成功')
        resetPasswordDialogVisible.value = false
      })
    }else{
      ElMessage.error('请按要求输入密码')
    }

  })
}
</script>

<style scoped>
.user-management {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.operation-buttons {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>